<template>
  <div class="home-page">
    <div v-if="loading" id="loading">Loading...</div>
    <div v-else class="page-main-content"  @click="dropdownClose">
      <aside class="left-price">
        <div class="left-price-top-type">{{ currentGeo }}</div>
        <ul>
          <li v-for="price in [...leftPriceList[currentGeo]].reverse()">{{ curSymb[currentGeo] }}{{ price }}
          </li>
        </ul>
      </aside>
      <main class="content-row-list">
        <ul class="row-list-top-header">
          <li v-for="cqData in cqList">
            <div class="year-cq year-cq-1">CQ-{{ cqData.cq }} {{ cqData.year }}</div>
            <div class="cq-month">
              <span v-for="month in cqData.months">{{ monthsList[month - 1] }}</span>
            </div>
          </li>
        </ul>
        <ul class="project-content-list">
          <li v-for="price in [...leftPriceList[currentGeo]].reverse()" :key="price"
              :class="{ borderBottom: rppSep[currentGeo].includes(price)}"
              :style="`height:calc(100% / ${leftPriceList[currentGeo].length})` "  @mouseenter="projectInfoLeave">

            <template v-for="quarterData in cqList">
              <div v-for="(monthProject, index) in quarterData.months"
                   :class="{'border-right': index === 2, 'project-content-item': true }"
                   :data-price="price"
                   :data-month="monthProject"
                   :data-year="quarterData.year"
                   @click.stop.prevent="projectItemEmptyClick">

                <span v-if="getProductByDate(quarterData.year, monthProject, price).projectName"
                      class="project-content-item-span"
                      :data-price="price"
                      :data-month="monthProject"
                      :data-year="quarterData.year"
                      :data-id="getProductByDate(quarterData.year, monthProject, price).projectId"
                      @mouseenter.stop="projectInfoEnter"
                      @click.stop.prevent="projectItemClick">
                    <span v-if="getProductByDate(quarterData.year, monthProject, price).network"
                          :style="{ borderColor: getProductByDate(quarterData.year, monthProject, price).defColor }"
                          class="network-mark">
                      {{ getProductByDate(quarterData.year, monthProject, price).network }}
                    </span>
                    <span class="project-item-content" :style="{ backgroundColor: getProductByDate(quarterData.year, monthProject, price).defColor }">
                      {{ getProductByDate(quarterData.year, monthProject, price).projectName }}
                    </span>
                </span>
              </div>
            </template>
          </li>
        </ul>
      </main>
    </div>

    <a-dropdown v-model:open="dropMenuVisible">
      <span class="el-dropdown-link" :style="menuStyle"></span>
      <template #overlay>
        <a-menu @click="dropMenuCommand">
          <!-- 点击空白处 显示的操作菜单 -->
          <template v-if="actionMenuType === 'action'">
            <template v-for="item in systemControls">
              <a-menu-item v-if="item.isPerm" :key="item.perms">{{ item.title }}</a-menu-item>
              <a-sub-menu v-else :title="item.title" :key="item.title">
                <a-menu-item v-for="childItem in item.children" :key="childItem.perms">{{ childItem.title }}</a-menu-item>
              </a-sub-menu>
            </template>
          </template>
          <!-- 点击项目， 显示的操作菜单 -->
          <template v-else>
            <template v-for="item in userActionControls">
              <a-menu-item v-if="item.isPerm" :key="item.perms">{{ item.title }}</a-menu-item>
              <a-sub-menu v-else :title="item.title" :key="item.title">
                <a-menu-item v-for="childItem in item.children" :key="childItem.perms">{{ childItem.title }}</a-menu-item>
              </a-sub-menu>
            </template>
          </template>

        </a-menu>
      </template>
    </a-dropdown>

<!--    <a-popover title="Title" v-model:open="popVisible" placement="rightBottom" :autoAdjustOverflow="false" :overlayStyle="menuStyle">-->
<!--      <template #content>-->
<!--        <div id="projectMouseContent" style="width: 30vw;height: 45vh;"></div>-->
<!--      </template>-->
<!--      <span  class="el-dropdown-link" ></span>-->
<!--    </a-popover>-->
    <div v-show="popVisible" class="project-content-info" :style="projectPopover">
      <table >
        <tr v-for="(rowData, index) in mouseTopData" :key="index">
          <td width="150">{{ rowData.label }}</td>
          <td>{{ getPopoverData(rowData) }}</td>
        </tr>
      </table>
    </div>


  </div>

  <add-project-modal ref="addProjectModal" @success="getData"/>
  <edit-specs-modal ref="editSpecsModal" @success="getData"/>
  <edit-dimension-modal ref="editDimensionModal" @success="getData"/>
  <view-tmc-modal ref="viewTmcModal" />
  <view-specs-modal ref="viewSpecsModal"/>
</template>

<script>
import {cqList, getTMCTotal, monthsList, mouseTopData} from "@/views/home/config";
import addProjectModal from "@/views/modals/addProjectModal.vue";
import request from "@/utils/request";
import {message} from "ant-design-vue";
import EditSpecsModal from "@/views/modals/editSpecsModal.vue";
import EditDimensionModal from "@/views/modals/editDimensionModal.vue";
import usePermissionStore from '@/store/modules/permission'
import moment from "moment";
import viewTMCModal from "@/views/modals/viewTMCModal";
import viewSpecsModal from "@/views/modals/viewSpecsModal";

export default {
  name: 'homeIndex',
  components: {
    EditSpecsModal,
    addProjectModal,
    EditDimensionModal,
    viewTmcModal: viewTMCModal,
    viewSpecsModal
  },
  data() {
    return {
      loading: true,
      popVisible: false,
      leftPriceList: window.systemConfig.projectTags,
      rppSep: window.systemConfig.rppSep,
      curSymb: window.systemConfig.curSymb,
      monthsList,
      currentGeo: 'ROW',
      popoverData: {},
      menuStyle: {
        top: 0,
        left: 0
      },
      projectPopover: {},
      dropMenuVisible: false,
      dropProjectMenuVisible: false,
      actionMenuType: 'action',
      cqList: [],
      projectList: [],
      systemControls: [],
      userActionControls: [],
      projectMap: {},
      clickItemData: {},
      mouseTopData,
      currentDate: new Date()
    }
  },
  created() {
    this.createCqData()
  },
  mounted() {
    const permissionStore = usePermissionStore()
    this.systemControls = permissionStore.systemControls
    this.userActionControls = permissionStore.userActionControls
    this.getData()
    document.addEventListener('keypress', (e) => {
      if (e.shiftKey && e.key === '<') {
        this.currentDate.setMonth(this.currentDate.getMonth() - 3)
        this.createCqData()
      }
      if (e.shiftKey && e.key === '>') {
        this.currentDate.setMonth(this.currentDate.getMonth() + 3)
        this.createCqData()
      }
    })
  },
  methods: {
    getPopoverData(rowData) {
      let { row, unit, type } = rowData
      if (row === 'TMC') {
        return getTMCTotal(this.popoverData)
      }
      if (typeof row === "string") {
        let data = this.doGetPopoverData(row);
        data = data + ' ' + (data ? (unit || '') : '')
        return type === 'date' ? moment(data.split('T')[0]).format('YYYY-MM') : data
      }
      if (row instanceof Array) {
        const list = row.map(item => {
          return this.doGetPopoverData(item)
        })
        let str = ''
        list.forEach((data) => {
          if (data !== '') {
            str += str !== '' ? ` x ${data}` : data
          }
        })
        return str === '' ? '' : `${str} ${unit}`
      }
      return ''
    },
    doGetPopoverData(row) {
      if (typeof row === "string") {
        if (row.includes('.')) {
          const strArr = row.split('.')
          let data = this.popoverData[strArr[0]]
          // 如果是对象的，则取 price
          data = data ? data[strArr[1]] : ''

          if (typeof data === 'object') {
            return data.price || ''
          }
          return data
        }
        return this.popoverData[row]
      }
      return ''
    },
    getData() {
      request({
        url: '/project/list',
        method: 'get',
      }).then(response => {
        if (response.code === 200) {
          this.projectList = response.data
          const obj = {}
          this.projectList.forEach(item => {
            item.specs = item.specs[0]
            item.dimension = item.dimensions[0]
            const ok2Ship = new Date(item.ok2Ship)
            obj[this.createProjectId(ok2Ship.getFullYear(), ok2Ship.getMonth() + 1, item.rpp)] = item
          })

          this.projectMap = obj
        }
      }).finally(() => {
        this.loading = false
      })
    },
    projectInfoEnter(event) {
      if (this.dropMenuVisible) {
        return
      }
      const el = event.target
      const rectData = el.getBoundingClientRect()
      const styleObj = {}
      const windowStyle = {
        width: window.innerWidth,
        height: window.innerHeight,
      }

      if (rectData.x > windowStyle.width / 2) {
        styleObj.right = windowStyle.width - rectData.x
      } else {
        styleObj.left = rectData.width + rectData.left
      }

      if (rectData.y > windowStyle.height / 2) {
        styleObj.bottom = windowStyle.height - rectData.y - rectData.height + 5
      } else {
        styleObj.top = rectData.top + 5
      }
      Object.keys(styleObj).forEach(key => {
        styleObj[key] += 'px'
      })
      this.projectPopover = styleObj
      this.popoverData = this.getProductByDate(el.getAttribute('data-year'), el.getAttribute('data-month'), el.getAttribute('data-price'))
      this.popVisible = true
    },
    projectInfoLeave() {
      this.menuStyle.top = 0
      this.menuStyle.left = 0
      this.popVisible = false
    },
    createProjectId(year, month, rpp) {
      return `${year}-${month}-${rpp}-${this.currentGeo}`
    },
    getProductByDate(year, month, rpp) {
      return this.projectMap[this.createProjectId(year, month, rpp)] || {}
    },
    createCqData() {
      const currentDate = this.currentDate
      const month = currentDate.getMonth() + 1
      const currentYear = currentDate.getFullYear()

      const currentCq = parseInt(month / 3, 10) + 1
      const list = []
      for (let i = 0; i < 4; i++) {
        let cq = currentCq + i
        let year = cq > 4 ? currentYear + 1 : currentYear
        cq = cq > 4 ? cq - 4 : cq
        list.push({
          year: year,
          cq: cq,
          months: cqList[cq - 1]
        })
      }
      this.cqList = list
    },
    //  项目格子 空白区域点击
    projectItemEmptyClick(event) {
      if (this.dropMenuVisible) {
        document.querySelectorAll('.active').forEach(el => {
          el.classList.remove('active')
        })
        return this.dropMenuVisible = false
      }
      this.clickItemData = {
        year: event.target.getAttribute('data-year'),
        month: event.target.getAttribute('data-month'),
        rpp: event.target.getAttribute('data-price'),
        geo: this.currentGeo
      }
      this.actionMenuType = 'action'
      document.querySelectorAll('.active').forEach(el => {
        el.classList.remove('active')
      })
      event.target.classList.add('active')
      this.menuStyle.top = event.clientY + 'px'
      this.menuStyle.left = (event.clientX + 5) + 'px'
      this.dropMenuVisible = true
    },
    // 项目数据点击
    projectItemClick(event) {
      this.projectInfoLeave()
      if (this.dropMenuVisible) {
        document.querySelectorAll('.active').forEach(el => {
          el.classList.remove('active')
        })
        return this.dropMenuVisible = false
      }
      const targetEl = event.target.classList.contains('project-item-content') ? event.target.parentElement : event.target
      this.clickItemData = {
        year: targetEl.getAttribute('data-year'),
        month: targetEl.getAttribute('data-month'),
        rpp: targetEl.getAttribute('data-price'),
        geo: this.currentGeo
      }

      this.actionMenuType = 'project'
      document.querySelectorAll('.active').forEach(el => {
        el.classList.remove('active')
      })
      targetEl.classList.add('active')
      this.menuStyle.top = event.clientY + 'px'
      this.menuStyle.left = (event.clientX + 5) + 'px'
      this.dropMenuVisible = true
    },
    dropdownClose() {
      // this.dropMenuVisible = true
    },
    deleteProject() {
      const projectData = this.getProductByDate(this.clickItemData.year, this.clickItemData.month, this.clickItemData.rpp)
      request({
        url: '/project/remove',
        method: 'post',
        data: {
          projectId: projectData.projectId
        }
      }).then(response => {
        if (response.code === 200) {
          message.success('delete success')
          this.getData()
        } else {
          message.warning('delete fail')
        }
      })
    },
    /**
     * 编辑、查看specs
     * @param isView true查看， false 编辑
     */
    editSpecs(isView = false) {
      const projectData = this.getProductByDate(this.clickItemData.year, this.clickItemData.month, this.clickItemData.rpp)
      request({
        url: '/specs/detail',
        method: 'post',
        data: {
          projectId: projectData.projectId
        }
      }).then(response => {
        if (response.code === 200 && response.data) {
          if (isView) {
            this.$refs.viewTmcModal.show({ ...response.data, projectName: projectData.projectName })
          } else {
            this.$refs.editSpecsModal.show({ ...response.data, projectName: projectData.projectName })
          }
        }
      })
    },
    editDimension() {
      const projectData = this.getProductByDate(this.clickItemData.year, this.clickItemData.month, this.clickItemData.rpp)
      request({
        url: '/dimension/detail',
        method: 'post',
        data: {
          projectId: projectData.projectId
        }
      }).then(response => {
        if (response.code === 200 && response.data) {
          this.$refs.editDimensionModal.show({ ...response.data, projectName: projectData.projectName })
        }
      })
    },
    dropMenuCommand({ key }) {
      console.log(key, 'key')
      this.dropMenuVisible = false
      if (key === 'createProject') {
        this.$refs.addProjectModal.show(this.clickItemData)
      }

      if (key === 'editProject') {
        const projectData = this.getProductByDate(this.clickItemData.year, this.clickItemData.month, this.clickItemData.rpp)
        this.$refs.addProjectModal.edit(projectData)
      }

      if (key === 'deleteProject') {
        this.deleteProject()
      }

      if (key === 'editSpecs') {
        this.editSpecs()
      }

      if (key === 'editDimensions') {
        this.editDimension()
      }

      if (key === 'about') {
        this.$router.push('/system/user')
      }

      if (key.includes('_Roadmap')) {
        const splitKey = key.split('_')[0]
        this.currentGeo = splitKey
      }

      if (key === 'view_TMC') {
        this.editSpecs(true)
      }

      if (key === 'viewSpecs') {
        this.$refs.viewSpecsModal.show(this.popoverData)
      }
    },
  }
}
</script>

<style scoped lang="less">
@import "./index.less";
.home-page{
  position: relative;
  .el-dropdown-link{
    position: absolute;
  }
  .project-content-item.active{
    background-color: #00264d;
  }
  .project-content-item-span{
    display: inline-block;
    width: 100%;
    height: 100%;
    padding: 5px;
    &.active{
      background-color: #00264d;
    }
    .project-item-content{
      background: pink;
      color: #FFFFFF;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
    }
  }

  .network-mark{
    width: 2.8rem;
    height: 2.8rem;
    font-size: 1.4rem;
    line-height: 2rem;
    border-radius: 50%;
    position: absolute;
    top: -0.7rem;
    left: -0.7rem;
    background-color: #00264d;
    border: 4px solid ;
  }
}

.project-content-info{
  position: fixed;
  background: rgba(255,255,255, 0.9);
  width: 35vw;
  border-radius: 5px;
  padding: 5px;
  tr{
    td:first-child{
      color: #444;
      padding: 1px 10px;
    }
    td:last-child{
      color: #000;
    }
  }
}
</style>
